package com.meepo.feed.comment

import android.annotation.SuppressLint
import android.os.Bundle
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.meepo.sdk.utils.SpanUtils
import com.meepo.basic.router.RouterManager
import com.meepo.basic.router.RouterManager.FeedModule.CommentReplyListFragment_Path
import com.meepo.basic.components.listfragment.MeepoListFragment
import com.meepo.basic.components.listfragment.ListFragmentParams
import com.meepo.feed.API
import com.meepo.feed.R
import com.meepo.basic.schema.Enums
import com.meepo.basic.schema.common.PageResult
import com.meepo.basic.schema.common.ResponseWrapper
import com.meepo.basic.schema.feed.Comment
import com.meepo.basic.schema.feed.CommentReq
import com.meepo.framework.design.imageview.CircularImage
import com.meepo.framework.design.input.InputDialog
import com.meepo.framework.design.recycler.ViewHolder
import com.meepo.framework.design.tag.BasicTag
import com.meepo.framework.design.tag.TagView
import com.xiaojinzi.component.anno.FragmentAnno
import com.xiaojinzi.component.support.ParameterSupport
import io.reactivex.Observable

/**
 * @author
 *
 * @date  11/14/20 7:55 PM
 * @version 1.0
 */
@FragmentAnno(CommentReplyListFragment_Path)
class CommentReplyListFragment : MeepoListFragment<Comment>() {

    companion object {
        fun instance(
            mItemId: String = "",
            mainCommentId: String = "",
//            atUserId: String = "",
//            authorId: String = "",
            forDisplay: Boolean = false,
            listFragmentParams: ListFragmentParams = ListFragmentParams()
        ): CommentReplyListFragment {
            val rsp = CommentReplyListFragment()
            val bundle = Bundle()
            bundle.putString("mItemId", mItemId)
            bundle.putString("mainCommentId", mainCommentId)
//            bundle.putString("atUserId", atUserId)
//            bundle.putString("authorId", authorId)
            bundle.putBoolean("forDisplay", forDisplay)
            bundle.putSerializable("listFragmentParams", listFragmentParams)
            rsp.arguments = bundle
            return rsp
        }
    }

    override fun loadDataObservable(page: Int): Observable<ResponseWrapper<PageResult<Comment>>> {
        val mainCommentId = ParameterSupport.getString(requireArguments(), "mainCommentId") ?: ""

        return API.instance().fetchCommentReplies(mainCommentId, page)
    }

    @SuppressLint("SetTextI18n")
    override fun bind(item: Comment, holder: ViewHolder, position: Int) {

        val mItemId = ParameterSupport.getString(requireArguments(), "itemId") ?: ""
        val mainCommentId = ParameterSupport.getString(requireArguments(), "mainCommentId") ?: ""
//        val atUserId = ParameterSupport.getString(requireArguments(), "atUserId") ?: ""
//        val authorId = ParameterSupport.getString(requireArguments(), "authorId") ?: ""
        val forDisplay = ParameterSupport.getBoolean(requireArguments(), "forDisplay") ?: false

        // 头像
        holder.getView<CircularImage>(R.id.avatar_ci)?.let {
            holder.setImagePath(R.id.avatar_ci, item.author?.avatar ?: "")
            it.setOnClickListener {
                item.author?.id?.let { userId ->
                    RouterManager.UserModule.routeToUserProfile(requireContext(), userId)
                }
            }
        }

        // 昵称
        holder.getView<TextView>(R.id.username_tv)?.let {
            it.text = item.author?.nickname ?: ""
            it.setOnClickListener {
                item.author?.id?.let { userId ->
                    RouterManager.UserModule.routeToUserProfile(requireContext(), userId)
                }
            }
        }

        holder.getView<TagView>(R.id.tag_tv)?.let {
            item.author?.getTag()?.let { tag ->
                it.text = tag
            }

            if (item.author?.getTag() == null) {
                it.visibility = View.GONE
            }
        }

        // 喜欢
        holder.setText(R.id.like_count_tv, "" + item.getLikeCount())

        val likeColor = requireContext().resources.getColor(R.color.like)
        val normalColor = requireContext().resources.getColor(R.color.primary_text_color)

        holder.getView<ImageView>(R.id.like_iv)?.let { imageView ->
            if (item.isLiked()) {
                imageView.setImageResource(R.drawable.ic_like)
                imageView.setColorFilter(likeColor)
            } else {
                imageView.setImageResource(R.drawable.ic_like_line)
                imageView.setColorFilter(normalColor)
            }
        }

        holder.getView<LinearLayout>(R.id.like_ll)?.setOnClickListener {
            presenter.call(
                API.instance()
                    .addAction(item.id, Enums.ITEM_TYPE_COMMENT, Enums.ACTION_TYPE_LIKED, cancel = if (item.isLiked()) 1 else 0)
            )

            this.replace(position, item.switchLiked())
        }

        holder.getView<TextView>(R.id.like_count_tv)?.let {
            it.text = "" + item.getLikeCount()
            it.setTextColor(if (item.isLiked()) likeColor else normalColor)
        }

        // 评论内容
        holder.getView<TextView>(R.id.content_tv)?.let { textView ->

            if (item.atUser != null) {
                com.meepo.sdk.utils.SpanUtils.with(textView).append("回复 ")
                    .append(" ${item.atUser?.nickname ?: ""} : ")
                    .setClickSpan(object : ClickableSpan() {
                        override fun onClick(p0: View) {
                            item.atUser?.id?.let {
                                RouterManager.UserModule.routeToUserProfile(requireContext(), it)
                            }
                        }

                        override fun updateDrawState(ds: TextPaint) {
                            ds.color = resources.getColor(R.color.primary_color);
                            ds.isUnderlineText = false
                        }
                    })
                    .append(item.content ?: "")
                    .create()
            } else {
                textView.text = item.content ?: ""
            }

        }


        // @的评论
        holder.setVisibility(R.id.reply_to_comment, View.GONE)

        item.atUser?.let {
            holder.setVisibility(R.id.reply_to_comment, View.VISIBLE)
            holder.setText(R.id.reply_to_comment, "@${it.nickname}: ${""}")
        }

        // 回复
//        holder.getView<BasicTag>(R.id.reply_tag)?.let {
//            it.setOnClickListener {
//
//                // 评论的评论不打开新的页面
//                if (mainCommentId != "") {
//                    showInputDialog(item.id, "回复 ${item.author?.nickname} :")
//                } else {
//
//                    RouterManager.FeedModule.routeToFeedCommentReply(requireContext(), item.id)
//                }
//            }
//        }

        holder.itemView.setOnClickListener {
            showInputDialog(mItemId, mainCommentId, item.id, "回复 ${item.author?.nickname} :")
        }


        if (forDisplay) {

            holder.getView<BasicTag>(R.id.reply_tag)?.visibility = if (forDisplay) View.GONE else View.VISIBLE

            holder.itemView.setOnClickListener {
                if (item.atCommentId != "") {
                    RouterManager.FeedModule.routeToFeedCommentReply(requireContext(), commentId = item.atCommentId!!)
                } else {
                    RouterManager.FeedModule.routeToFeedComment(requireContext(), itemId = item.itemId)
                }

            }
        }

        // 时间
        holder.setText(R.id.time_tv, item.createdAt ?: "")
    }

    private fun showInputDialog(itemId: String, mainCommentId: String, atCommentId: String = "", tintText: String = "") {
        InputDialog(tintText, object : InputDialog.InputListener {
            override fun onSubmit(inputText: String) {

                presenter.call(
                    API.instance().addComment(
                        CommentReq(
                            itemId = itemId,
                            content = inputText,
                            mainCommentId = mainCommentId,
                            atCommentId = atCommentId
                        )
                    ),
                    { rsp -> rsp.data?.let { insert(it) } },
                    { }

                )
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

        }).show(childFragmentManager, "aaa")
    }

    override fun getItemViewLayoutId(item: Comment, position: Int): Int = R.layout.comment_reply_list_item_layout
}